package com.demo.netty.client;

import com.demo.netty.handler.NettyClientHandler;
import com.demo.netty.protocol.HeatbeatEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author liangliang
 */
@Component
public class NettyClientA {

    @Value("${netty.server.host}")
    private String host;
    @Value("${netty.server.port}")
    private int port;

    private EventLoopGroup group = new NioEventLoopGroup();

    private SocketChannel socketChannel;

    @PostConstruct
    public void start() throws InterruptedException {

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    channel.pipeline()
                        // 10秒没有发送消息，将IdleStateHandler 添加到ChannelPipeLine中
                        .addLast(new IdleStateHandler(0, 10, 0))
                        .addLast(new HeatbeatEncode())
                        .addLast(new NettyClientHandler());
                }
            });

        ChannelFuture future = bootstrap.connect(host, port).sync();
        if (future.isSuccess()) {
            System.out.println("启动 Netty 成功");
        }
        socketChannel = (SocketChannel)future.channel();
    }
}
